package com.zyguo.thread;

import java.util.ArrayList;


public class ThreadGroup_activecount {
	public static void main(String[] args) {
		int threadNum = 10;
		final ThreadGroup tgroup = new ThreadGroup("test-threadgroup");
		ArrayList<Thread> tList = new ArrayList<>();
		//定义10个线程
		for( int i = 0; i < threadNum; i++ ){
			Thread t = new Thread( tgroup, new SleepRunnable( 5000 + i*1000) ,"test-thread-" + i);
			tList.add( t );
		}

		System.out.println("before start, activeCount=" + tgroup.activeCount() );

		//检验 enumerate 方法
		Thread[] threads = new Thread[threadNum];
		//获取所有的子线程
		int num = tgroup.enumerate( threads );
		System.out.println( "befor start thread, enumerate num=" + num );
		for (Thread thread : tList) {
			thread.start();
			System.out.println("start thread = " + thread );
		}
		num = tgroup.enumerate( threads );
		System.out.println( "all thread start, enumerate num=" + num );
		
		//监控线程的活动的子线程数
		Thread t = new Thread( new Runnable() {
			@Override
			public void run() {
				int activeCount = tgroup.activeCount();
				while ( activeCount > 0 ) {
					System.out.println("activeCount=" + activeCount );
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					activeCount = tgroup.activeCount();
				}
				System.out.println("all thread is stop, activeCount=" + activeCount );		
			}
		});
		
		t.start();
		
		
		
		
		
	}
}

